package com.heba.fragment.scan;

import android.content.res.Resources;
import android.os.Bundle;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.material.tabs.TabLayout;
import com.heba.adapter.FmPagerAdapter;
import com.heba.config.CommonConfig;
import com.heba.event.MessageEvent;
import com.heba.fragment.BaseFragment;
import com.heba.greenmulu.R;
import com.heba.greenmulu.scan.ItemHistoryEditActivity;
import com.heba.greenmulu.scan.ItemProductCategoryActivity;
import com.heba.greenmulu.scan.ItemSavedEditActivity;
import com.heba.greenmulu.scan.ItemScanSearchActivity;
import com.heba.utils.IndicatorLineUtil;
import com.heba.view.ClearEditTextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

/**
 * 扫描界面
 * <p>
 * Created by jason on 2019/2/13.
 */

public class ScanFragment extends BaseFragment {

    private ClearEditTextView clearEditTextView;
    private ImageView img_category;
    private TextView txt_edit;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private FmPagerAdapter pagerAdapter;
    private ArrayList<Fragment> fragments = new ArrayList<>();
    private String[] strings;
    private int selectIndex = 1;

    private ConstraintLayout bottomLine1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onVisible() {
        super.onVisible();
        EventBus.getDefault().post(new MessageEvent(CommonConfig.SCAN_VISIBLE));
    }

    @Override
    protected void onHidden() {
        super.onHidden();
        EventBus.getDefault().post(new MessageEvent(CommonConfig.SCAN_HIDDEN));
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_scan, null);
        initView(view);
        return view;
    }

    /**
     * initView
     *
     * @param view
     */
    private void initView(View view) {
        clearEditTextView = view.findViewById(R.id.clearEditText);
        txt_edit = view.findViewById(R.id.txt_right);
        img_category = view.findViewById(R.id.img_right);
        tabLayout = view.findViewById(R.id.tablayout);
        viewPager = view.findViewById(R.id.viewpager);
        bottomLine1 = view.findViewById(R.id.bottom_line_1);
        txt_edit.setText(getContext().getResources().getString(R.string.edit));
        txt_edit.setVisibility(View.GONE);
        img_category.setVisibility(View.GONE);

        //点击edittex跳转
        clearEditTextView.clearFocus();
        clearEditTextView.setOnEditTextListener(new ClearEditTextView.OnEditTextListener() {
            @Override
            public void onDeleteClick() {

            }

            @Override
            public void afterTextChanged(String text) {

            }

            @Override
            public void onSearchClick(String text) {

            }

            @Override
            public void onIntent() {
                openActivity(ItemProductCategoryActivity.class);
            }
        });

        img_category.setImageResource(R.drawable.icon_scan_classify);
        img_category.setOnClickListener(v -> openActivity(ItemProductCategoryActivity.class));

        //添加tab标题数据
        strings = getActivity().getResources().getStringArray(R.array.array_scan);

        /**
         * 添加fragment
         */
        fragments.add(new SavedScanFragment());
        fragments.add(new BarScanFragment());
        fragments.add(new HistoryScanFragment());

        /**
         * 添加tab
         */
        for (int i = 0; i < strings.length; i++) {
            tabLayout.addTab(tabLayout.newTab());
        }

        /**
         * 关联viewpager,设置adapter
         */
        tabLayout.setupWithViewPager(viewPager, false);
        pagerAdapter = new FmPagerAdapter(fragments, getChildFragmentManager());
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOffscreenPageLimit(3);

        /**
         * 设置tab文字,必须在关联viewpager之后设置，否则文字不显示
         */
        for (int i = 0; i < strings.length; i++) {
            tabLayout.getTabAt(i).setText(strings[i]);
        }

        /**
         * 默认选中第二个卡
         */
        img_category.setVisibility(View.GONE);
        tabLayout.getTabAt(1).select();

        /**
         * 设置指示线长度间隔(单位dp)
         */
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                IndicatorLineUtil.setIndicator(tabLayout, 0, 0);
            }
        });


        /**
         * tabLayout监听滑动指示卡
         */
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

                int position = tabLayout.getSelectedTabPosition();
                Resources resources = getResources();
                DisplayMetrics dm = resources.getDisplayMetrics();
                int width3 = dm.widthPixels;


                TranslateAnimation translateAnimation1 = new TranslateAnimation((selectIndex-1)*(width3/3),(position-1)*(width3/3),0,0);
                translateAnimation1.setDuration(300);
                translateAnimation1.setFillEnabled(true);//使其可以填充效果从而不回到原地
                translateAnimation1.setFillAfter(true);//不回到起始位置
                bottomLine1.startAnimation(translateAnimation1);


                translateAnimation1.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        selectIndex = tabLayout.getSelectedTabPosition();
//


                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
                switch (tab.getPosition()) {
                    case 0:
                        EventBus.getDefault().post(new MessageEvent(CommonConfig.SCAN_MY_PRODUCT));
                        img_category.setVisibility(View.INVISIBLE);
                        txt_edit.setVisibility(View.VISIBLE);
                        clearEditTextView.setVisibility(View.GONE);
                        break;
                    case 1:
                        EventBus.getDefault().post(new MessageEvent(CommonConfig.SCAN_BAR_SCAN));
                        img_category.setVisibility(View.GONE);
                        txt_edit.setVisibility(View.GONE);
                        clearEditTextView.setVisibility(View.VISIBLE);
                        break;
                    case 2:
                        EventBus.getDefault().post(new MessageEvent(CommonConfig.SCAN_HISTORY));
                        img_category.setVisibility(View.INVISIBLE);
                        txt_edit.setVisibility(View.VISIBLE);
                        clearEditTextView.setVisibility(View.GONE);
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        /**
         * 监听edit事件，显示删除按钮
         */
        txt_edit.setOnClickListener(v -> {
            switch (tabLayout.getSelectedTabPosition()) {
                case 0:
                    //编辑用户收藏产品列表
                    openActivity(ItemSavedEditActivity.class);
                    break;
                case 2:
                    //编辑用户扫描产品历史列表
                    openActivity(ItemHistoryEditActivity.class);
                    break;
                default:
                    break;

            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        /**
         * 接收事件
         */
        if (event.getEvent().equals(CommonConfig.SCAN_REFRESH)) {
            if (null != tabLayout && tabLayout.getTabCount() > 0) {
                tabLayout.getTabAt(1).select();
            }
        }
    }
}
